const {getPsdSha256, getTime, getNextId, checkPsd, getToken, getHeaderToken, verifyToken} = require("../../util");
const responseResult = require("../../util/responseResult");
const {request} = require("../../util/index")
const {regisSql, isUserExitsSql, loginSql, updateLoginTime, deleteUser} = require("../../model/authorModel");
const {Router} = require("express");
const {isBodyData} = require("../../middleware");
const paths = {
    login: "/login",
    info: "/info",
    register: "/register",
    update: "/:id",
    exit: "/exit",
    delete: "/log_off"
}


const userRouter = Router();

// 注册用户参数验证
const registerVerify = (req, res, next) => {
    const {config_password, password, email, sex} = req.body;
    // 邮箱正则
    const emailTest = /^\w{3,}(\.\w+)*@[A-z0-9]+(\.[A-z]{2,5}){1,2}$/;
    if (config_password !== password) {
        return res.json(responseResult.error("两次输入的密码不一致"));
    }
    if (!emailTest.test(email)) {
        return res.json(responseResult.error("请输入正确的邮箱"));
    }
    if (sex !== 1 && sex !== 2) {
        return res.json(responseResult.error("性别参数值不正确"))
    }
    isUserExitsSql({email: req.body.email}, res, (results, fields) => {
        if (results[0].count > 0) {
            res.json(responseResult.error("邮箱已被注册"))
        } else {
            isUserExitsSql({username: req.body.username}, res, (results, fields) => {
                if (results[0].count > 0) {
                    return res.json(responseResult.error("用户名已被注册"))
                } else {
                    next();
                }
            })
        }
    })
}

/**
 * @swagger
 * /pc/user/register:
 *   post:
 *     tags:
 *       - http相关
 *     summary: 用户注册
 *     consumes: application/json
 *     parameters:
 *       - in: body
 *         name: requestBody
 *         required: true
 *         schema:
 *           type: object
 *           properties:
 *             username:
 *               type: string
 *               title: 用户名
 *               required: true
 *             password:
 *               type: string
 *               title: 密码
 *               required: true
 *             config_password:
 *               type: string
 *               title: 确认密码
 *               required: true
 *             sex:
 *               type: number
 *               title: 性别
 *               required: true
 *               description: 1男 2女
 *             email:
 *               type: string
 *               title: 邮箱
 *               required: true
 *             avatar_id:
 *               type: string
 *               title: 头像id
 *               required: false
 *     responses:
 *       200:
 *         description: 注册成功
 *         schema:
 *           type: object
 *           properties:
 *             code:
 *               type: number
 *               title: 状态值0或1
 *             message:
 *               type: string
 *               title: 注册成功
 *
 */
const register = (req, res) => {
    let body = req.body;
    body = {
        ...body, id: getNextId(),
        config_password: null,
        password: getPsdSha256(body.password),
        create_time: getTime()
    };
    return regisSql(body, res, () => {
        return res.json(responseResult.success("操作成功"))
    })
}

userRouter.post(paths.register, isBodyData(['username', 'password', 'config_password', 'sex', "email"]), registerVerify, register);


// 登录
const login = (req, res) => {
    const {username, password, isAvoid = false} = req.body;
    loginSql({username}, res, results => {
        // 没查询到
        if (!results.length) {
            return res.json(responseResult.error("账号或密码错误"));
        }
        // 查询到
        if (checkPsd(results[0].password, password)) {
            let token = '';
            const tokenData = {
                id: results[0].id,
                username: results[0].username,
                avatar_id: results[0].avatar_id
            }
            // 是否勾选七天免登陆
            if (isAvoid) {
                token = getToken(tokenData, '7 days');
                res.cookie('token', token, {maxAge: 7 * 60 * 60 * 24});
            } else {
                token = getToken(tokenData, process.env.JWT_EXP);
                res.cookie('token', token, {maxAge: 60 * 60 * 2});
            }
            // 更新token和登录时间
            updateLoginTime({username, token}, res, () => {
                return res.json(responseResult.success('登录成功'));
            })
        } else {
            // 查询但密码匹配错误
            res.json(responseResult.error('密码错误'));
        }
    })
}

/**
 * @swagger
 * /pc/user/login:
 *   post:
 *     tags:
 *       - http相关
 *     summary: 登录
 *     consumes: application/json
 *     parameters:
 *       - in: body
 *         name: requestBody
 *         required: true
 *         schema:
 *           type: object
 *           properties:
 *             username:
 *               type: string
 *               title: 用户名
 *               required: true
 *             password:
 *               type: string
 *               title: 密码
 *               required: true
 *     responses:
 *       200:
 *         description: 登录成功
 *         schema:
 *           type: object
 *           properties:
 *             code:
 *               type: number
 *               title: 状态值0或1
 *             message:
 *               type: string
 *               title: 登录成功
 */
userRouter.post(paths.login, isBodyData(['username', 'password']), login);

const exit = (req, res) => {
    const token = getHeaderToken(req);
    // 获取token参数
    verifyToken(token, (data) => {
        const username = data.data.username;
        updateLoginTime({username, token: null}, res, () => {
            res.clearCookie('token');
            res.json(responseResult.success("操作成功"))
        })
    });
}

/**
 * @swagger
 * /pc/user/exit:
 *   get:
 *     tags:
 *       - http相关
 *     summary: 退出登录
 *     parameters:
 *       - name: Authorization
 *         in: header
 *         description: Bearer Token
 *         required: true
 *         type: string
 *         format: "Bearer {token}"
 *     responses:
 *       200:
 *         description: 操作成功
 *         schema:
 *           type: object
 *           properties:
 *             code:
 *               type: number
 *               title: 0或者1或-1
 *             message:
 *               type: string
 *               title: 操作成功
 */
// 退出登录
userRouter.get(paths.exit, exit);

/**
 * 清除头像信息
 * @param String taken当前用户token
 * @param String 当前用户头像id
 */
const removeAvatar = (token, id, cb) => {
    const option = {
        method: "get",
        path: `/common/delete_avatar/${id}`,
        headers: {
            "Authorization": token
        }
    }
    request(option, data => {
        cb();
        // res.json(responseResult.success("操作成功", data))
    })
};
// 注销
const _delete = (req, res) => {
    const token = getHeaderToken(req);
    // 注销流程,解析token
    verifyToken(token, data => {
        const {id, avatar_id} = data.data;
        // 删除用户
        deleteUser({id}, res, () => {
            res.clearCookie('token');
            // 清除头像
            removeAvatar(token, avatar_id, () => {
                return res.json(responseResult.success("操作成功"));
            });
        })
    })
}

/**
 * @swagger
 * /pc/user/log_off:
 *   get:
 *     tags:
 *       - http相关
 *     summary: 用戶注销
 *     parameters:
 *       - name: Authorization
 *         in: header
 *         description: Bearer Token
 *         required: true
 *         type: string
 *         format: "Bearer {token}"
 *     responses:
 *       200:
 *         descriptions: 操作成功
 *         schema:
 *           type: object
 *           properties:
 *             code:
 *               type: number
 *             message:
 *               type: string
 *               title: 操作成功
 *
 */
// 注销
userRouter.get(paths.delete, _delete)

// 用户信息
const info = (req, res) => {

}

// 更新用户
const update = (req, res) => {

}

// 删除注销用户
// const _delete = (req, res) => {
//
// }

module.exports = userRouter
